package com.ruowei.modules.webSocket.pojo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruowei.modules.webSocket.domain.Message;

import javax.websocket.EncodeException;
import javax.websocket.EndpointConfig;
import java.util.HashMap;
import java.util.Map;

public class MessageEncoder implements javax.websocket.Encoder.Text<Message> {
    @Override
    public String encode(Message message) throws EncodeException {
        ObjectMapper objectMapper = new ObjectMapper();

        if (message == null) {
            return null;
        }
        try {
            //Instant返给浏览器的序列化结果格式不对，因此在这里手动转字符串
            Map<String, Object> result = new HashMap<>();
            result.put("id", message.getId());
            result.put("messageCode", message.getMessageCode());
            result.put("senderType", message.getSenderType());
            result.put("senderCode", message.getSenderCode());
            result.put("receiverCode", message.getReceiverCode());
            result.put("messageType", message.getMessageType());
            result.put("jumpPage", message.isJumpPage());
            result.put("title", message.getTitle());
            result.put("content", message.getContent());
            result.put("customMessage", message.getCustomMessage());

            result.put("createTime", message.getCreateTime().toEpochMilli());
            result.put("planSendTime", message.getPlanSendTime().toEpochMilli());

            result.put("read", message.isRead());
            result.put("readTime", message.getReadTime());
            return objectMapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void init(EndpointConfig endpointConfig) {

    }

    @Override
    public void destroy() {

    }
}
